<template>
    <div class="register-container">
        <div class="register-box">
            <div class="register-header">
                <h2>注册账号</h2>
            </div>
            <form @submit.prevent="handleRegister">
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" v-model="username" required placeholder="请输入用户名">
                </div>
                <div class="form-group">
                    <label for="email">邮箱</label>
                    <input type="email" id="email" v-model="email" required placeholder="请输入邮箱">
                </div>
                <div class="form-group">
                    <label for="phone">手机号码</label>
                    <input type="text" id="phone" v-model="phone" required placeholder="请输入手机号码">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" v-model="password" required placeholder="请输入密码">
                </div>
                <div class="form-group">
                    <label for="confirmPassword">确认密码</label>
                    <input type="password" id="confirmPassword" v-model="confirmPassword" required placeholder="请再次输入密码">
                </div>
                <div v-if="error" class="error-message">{{ error }}</div>
                <button type="submit" class="register-btn" :disabled="loading">
                    {{ loading ? '正在注册...' : '注册' }}
                </button>
            </form>
            <div class="register-footer">
                <p>已有账号？<router-link to="/login">立即登录</router-link></p>
            </div>
        </div>
        
        <!-- 注册成功弹窗 -->
        <div v-if="showSuccessModal" class="success-modal-overlay">
            <div class="success-modal">
                <div class="success-icon">
                    <i class="success-checkmark">✓</i>
                </div>
                <h3>注册成功</h3>
                <p>{{redirectCountdown}}秒后自动跳转到登录页面</p>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { api } from '@/network/api';

const username = ref('');
const email = ref('');
const phone = ref('');
const password = ref('');
const confirmPassword = ref('');
const loading = ref(false);
const error = ref<string | null>(null);
const router = useRouter();

// 验证码发送状态
const isSending = ref(false);
const countdown = ref(60);

// 注册成功弹窗状态
const showSuccessModal = ref(false);
const redirectCountdown = ref(3);
let redirectTimer: number | null = null;

// 表单验证
const isFormValid = computed(() => {
    return (
        username.value.trim() !== '' &&
        email.value.trim() !== '' &&
        phone.value.trim() !== '' &&
        password.value.trim() !== '' &&
        password.value === confirmPassword.value
    );
});

// 登录页面跳转倒计时
const startRedirectCountdown = () => {
    showSuccessModal.value = true;
    redirectCountdown.value = 3;
    
    redirectTimer = window.setInterval(() => {
        redirectCountdown.value--;
        if (redirectCountdown.value <= 0) {
            clearInterval(redirectTimer!);
            showSuccessModal.value = false;
            router.push('/login');
        }
    }, 1000);
};

// 注册处理
const handleRegister = async () => {
    // 表单验证
    if (!isFormValid.value) {
        if (password.value !== confirmPassword.value) {
            error.value = '两次输入的密码不一致';
        } else {
            error.value = '请完善所有注册信息';
        }
        return;
    }
    
    // 验证手机号码格式
    const phoneRegex = /^1[3456789]\d{9}$/;
    if (!phoneRegex.test(phone.value)) {
        error.value = '请输入正确的手机号码格式';
        return;
    }

    loading.value = true;
    error.value = null;

    try {
        const response = await api.registerShopkeeper({
            username: username.value,
            email: email.value,
            phone: phone.value,
            passwordHash: password.value,
        });
        // 检查是否成功
        if (response && response.data) {
            // 显示成功弹窗并开始倒计时
            startRedirectCountdown();
        } else {
            error.value = '注册失败，请稍后重试';
        }
    } catch (err: any) {
        const errorData = err.response?.data || err;
        
        // 检查是否是手机号已被注册错误
        if (errorData && errorData.code === 200 && errorData.message === '手机号已被注册') {
            error.value = '手机号已被注册，请使用其他手机号';
            phone.value = ''; // 清空手机号输入
        } 
        // 备用检测方法：通过文本内容匹配
        else if (typeof errorData?.message === 'string' && 
                 errorData.message.includes('手机号') && 
                 errorData.message.includes('注册')) {
            error.value = '手机号已被注册，请使用其他手机号';
            phone.value = '';
        }
        // 如果错误消息是字符串形式的JSON，尝试解析它
        else if (typeof err === 'string' && err.includes('手机号已被注册')) {
            error.value = '手机号已被注册，请使用其他手机号';
            phone.value = '';
        }
        else {
            // 其他错误情况
            error.value = errorData?.message || '注册时发生错误，请稍后重试';
        }
    } finally {
        loading.value = false;
    }
};
</script>

<style scoped>
.register-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f0f2f5;
    background-image: url('https://images.unsplash.com/photo-1548343163-cb7ef5658536?q=80&w=2070&auto=format&fit=crop');
    background-size: cover;
    background-position: center;
    padding: 20px 0;
    position: relative; /* 添加相对定位，用于弹窗定位 */
}

.register-box {
    width: 100%;
    max-width: 450px;
    padding: 40px;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(5px);
}

.register-header {
    text-align: center;
    margin-bottom: 30px;
}

.register-header h2 {
    font-size: 2em;
    color: #333;
    font-weight: 600;
    margin: 0;
}

.form-group {
    margin-bottom: 20px;
    text-align: left;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #555;
}

.form-group input {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 6px;
    font-size: 1em;
    box-sizing: border-box;
    transition: border-color 0.3s, box-shadow 0.3s;
}

.form-group input:focus {
    outline: none;
    border-color: #3498db;
    box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

/* 验证码输入组 */
.verification-code .code-input-group {
    display: flex;
    gap: 10px;
}

.verification-code input {
    flex: 1;
}

.verification-code .code-btn {
    padding: 0 15px;
    background-color: #3498db;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 0.9em;
    white-space: nowrap;
    cursor: pointer;
    transition: background-color 0.3s;
}

.verification-code .code-btn:hover {
    background-color: #2980b9;
}

.verification-code .code-btn:disabled {
    background-color: #bdc3c7;
    cursor: not-allowed;
}

.register-btn {
    width: 100%;
    padding: 12px;
    background-color: #3498db;
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 1.1em;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.2s;
}

.register-btn:hover {
    background-color: #2980b9;
    transform: translateY(-2px);
}

.register-btn:disabled {
    background-color: #bdc3c7;
    cursor: not-allowed;
    transform: none;
}

.error-message {
    color: #e74c3c;
    background-color: #fdd;
    border: 1px solid #e74c3c;
    border-radius: 6px;
    padding: 10px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 0.9em;
}

.register-footer {
    margin-top: 20px;
    text-align: center;
    font-size: 0.9em;
}

.register-footer a {
    color: #3498db;
    text-decoration: none;
    font-weight: 500;
}

.register-footer a:hover {
    text-decoration: underline;
}

/* 成功弹窗样式 */
.success-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.success-modal {
    background-color: white;
    border-radius: 12px;
    padding: 30px;
    width: 300px;
    text-align: center;
    box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
    animation: fadeIn 0.3s;
}

.success-icon {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background-color: #2ecc71;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto 20px;
}

.success-checkmark {
    color: white;
    font-size: 40px;
    line-height: 1;
}

.success-modal h3 {
    color: #333;
    font-size: 24px;
    margin: 0 0 10px;
}

.success-modal p {
    color: #666;
    margin: 0;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-20px); }
    to { opacity: 1; transform: translateY(0); }
}
</style> 